package web.beans;

import Weather.Cities;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by vanches on 18.1.15.
 */
public class CityBeans implements Serializable {
    private final File fileCity=new File("/home/vanches/Java/File/XML_File/Cities.xml");
    private List<Cities.Country> countries;
    private List<Cities.Country.City> cities;
    private String countryUser;


    @PostConstruct
    private void init(){
        Cities city;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Cities.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            city = (Weather.Cities) jaxbUnmarshaller.unmarshal(fileCity);
            countries=new ArrayList<Cities.Country>(city.getCountry());
        }

        catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    public void countrySet(ValueChangeEvent e){
        countryUser=e.getNewValue().toString();

        for(int i=0; i<countries.size();i++){
            if(countryUser.equals(countries.get(i).toString())){
                cities=new ArrayList<Cities.Country.City>(countries.get(i).getCity());
                break;
            }
        }
    }

    //region GET and SET

    public List<Cities.Country> getCountries() {
        return countries;
    }

    public void setCountries(List<Cities.Country> countries) {
        this.countries = countries;
    }

    public List<Cities.Country.City> getCities() {
        return cities;
    }

    public void setCities(List<Cities.Country.City> cities) {
        this.cities = cities;
    }

    public String getCountryUser() {
        return countryUser;
    }

    public void setCountryUser(String countryUser) {
        this.countryUser = countryUser;
    }

    //endregion

}
